/* -*- c++ -*- */
/*
 * Copyright 2007 Free Software Foundation, Inc.
 *
 * This file is part of GNU Radio
 *
 * GNU Radio is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * GNU Radio is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GNU Radio; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street,
 * Boston, MA 02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#define VERBOSE 1

#include <xstar_reed_solomon.h>
#include <cstdio>
#include <stdexcept>

extern "C" {
#include "rs.h"
}

static const int rs_init_symsize =     8;
static const int rs_init_gfpoly  = 0x11d;
static const int rs_init_fcr     =     0;	// first consecutive root
static const int rs_init_prim    =     1;	// primitive is 1 (alpha)

static const int N = (1 << rs_init_symsize) - 1;	// 255

xstar_reed_solomon_sptr
xstar_make_reed_solomon(int packet_size, int fec_size)
{
  return xstar_reed_solomon_sptr(new xstar_reed_solomon(packet_size, fec_size));
}

xstar_reed_solomon::xstar_reed_solomon(int packet_size, int fec_size)
  : d_packet_size(packet_size),
    d_fec_size(fec_size)
{
  assert (d_fec_size < d_packet_size);
  assert (d_packet_size <= N);

  d_rs = init_rs_char (rs_init_symsize, rs_init_gfpoly,
		       rs_init_fcr, rs_init_prim, d_fec_size);

  assert (d_rs != 0);
}

xstar_reed_solomon::~xstar_reed_solomon ()
{
  if (d_rs)
      free_rs_char (d_rs);
  d_rs = 0;
}

std::string
xstar_reed_solomon::encode (char* packet)
{
  unsigned char tmp[N];
  int payload_size = d_packet_size - d_fec_size;

  memset (tmp + payload_size, 0, N - d_packet_size);
  memcpy (tmp, packet, payload_size);

  encode_rs_char (d_rs, tmp, tmp + N - d_fec_size);

  return std::string((char*)tmp + N - d_fec_size, d_fec_size);
}

std::string
xstar_reed_solomon::decode (char* packet)
{
  unsigned char tmp[N];
  int payload_size = d_packet_size - d_fec_size;

  memset(tmp + payload_size, 0, N - d_packet_size);
  memcpy(tmp, packet, payload_size);
  memcpy(tmp + N - d_fec_size, packet + payload_size, d_fec_size);

  int corrections = decode_rs_char (d_rs, tmp, 0, 0);

  if (VERBOSE)
      fprintf(stderr, "xstar_reed_solomon::decode: %d errors corrected\n", corrections);

  if (-1 == corrections)
      return std::string(); // failed to decode, return empty string

  return std::string((char*)tmp, payload_size);
}
